# include <stdio.h>
# include <stdlib.h>
# include <stdarg.h>
# include <string.h>
# include "xcompiler.h"
# include "x_parse.tab.h"

FILE *outfile;

struct ast *
newast(char *name, int num, ...){
  struct ast *a = malloc(sizeof(struct ast));
  if(a == NULL){
    printf("malloc err!");
    exit(0);
  }
  va_list valist;
  va_start(valist, num);

  if(num>0){
    a->l = va_arg(valist, struct ast *);
    a->lineno = a->l->lineno;
    if(num>=2){
      for(int i=1;i<num;i++){
	a->r  = va_arg(valist, struct ast *);
      }
    }
  }
  else{
    a->lineno = va_arg(valist, int);
  }
  return a;
}

void eval(struct ast *a, int level){
  for(int i=0; i<level; i++){
    fprintf(stdout,"  ");
  }
  if(a->lineno != -1){
    fprintf(stdout,"%s ",a->name);
  }

  fprintf(stdout,"\n");
  eval(a->l, level+1);
  eval(a->r, level);
}

int main(int argc, char **argv){
  if(argc != 2){
    printf("arg err: argc = %d\n",argc);
    for(int i=0;i<argc;i++){
      printf("  arg[%d]:%s\n",i,argv[i]);
    }
    exit(0);
  }
  int namelength = strlen(argv[1]) - 2;
  char sourcefile[64], targetfile[64];
  extern FILE *yyin;

  strcpy(sourcefile, argv[1]);
  strncpy(targetfile,sourcefile,namelength);
  strcpy(targetfile+namelength,".ast");

/*
  yyin = fopen(sourcefile, "r");
  if(!yyin){
    printf("open sfile err!\n");
    exit(0);
  }

  outfile=fopen(targetfile,"w");
  if(NULL == outfile){
    fclose(yyin);
    printf("open tfile err!\n");
    exit(0);
  }
*/
  yyparse();

  fclose(yyin);
//  fclose(outfile);
}
